package com.syuchen.server.http.bio;

import com.alibaba.fastjson.JSON;
import com.syuchen.common.Invocation;
import com.syuchen.protocol.http.Request;
import com.syuchen.protocol.http.Response;
import com.syuchen.server.http.RequestParser;
import com.syuchen.server.http.ResponseSender;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class BioThread implements Runnable{

    private Socket connectSocket;
    private InputStream requestStream;
    private OutputStream outputStream;

    BioThread(Socket connectSocket){
        this.connectSocket = connectSocket;
        try {
            this.requestStream = connectSocket.getInputStream();
            this.outputStream = connectSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                //接收请求
                Request request = RequestParser.parseRequestStream(requestStream);
                //处理请求
                Invocation invocation = JSON.parseObject(request.getBody(), Invocation.class);
                Class<?> classImpl = Class.forName(invocation.getInterfaceName());
                Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                Object result =  method.invoke(classImpl.newInstance(), invocation.getParameters());
                //响应请求
//                Response response = HttpResponseEncoder.encode(JSON.toJSONString(result));
                ResponseSender.send((Response) result, outputStream);
            }
        } catch (Exception e) {
            try {
                System.out.println("超时或其他异常 回收连接");
                connectSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
